<template>
  <el-tabs type="border-card">
    <el-tab-pane label="商品基本信息">
      {{goodsFrom}}
      <el-form ref="form" :model="goodsFrom" label-width="120px">
        <el-form-item label="商品分类">
          <!--一级分类，调用的是后台的findAll()方法，查询所有的一级分类-->
          <el-select v-model="goodsFrom.goods.category1Id">
            <el-option v-for="cate in categories1" :label="cate.name" :value="cate.id"/>
          </el-select>
          <!--二级分类-->
          <el-select v-model="goodsFrom.goods.category2Id">
            <el-option v-for="cate in categories2" :label="cate.name" :value="cate.id"/>
          </el-select>
          <!--三级分类-->
          <el-select v-model="goodsFrom.goods.category3Id">
            <el-option v-for="cate in categories3" :label="cate.name" :value="cate.id"/>
          </el-select>
          模板id:{{goodsFrom.goods.typeTemplateId}}
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="goodsFrom.goods.goodsName" placeholder="商品名称"/>
        </el-form-item>
        <el-form-item label="品牌">
          <!--根据模板id得到品牌列表-->
          <el-select v-model="goodsFrom.goods.brandId">
            <el-option v-for="brand in brandList" :label="brand.text" :value="brand.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="goodsFrom.goods.caption"/>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="goodsFrom.goods.price"/>
        </el-form-item>
        <el-form-item label="商品介绍">
          <el-input v-model="goodsFrom.goodsDesc.introduction"/>
        </el-form-item>
        <el-form-item label="包装列表">
          <el-input v-model="goodsFrom.goodsDesc.packageList"/>
        </el-form-item>
        <el-form-item label="售后服务">
          <el-input v-model="goodsFrom.goodsDesc.saleService"/>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="商品图片">
      <el-button type="success" plain @click="newCreate">新建</el-button>
      <!--这里有个表格用来显示上传的图片-->
      <el-table
        :data="goodsFrom.goodsDesc.itemImages"
        style="width: 100%">
        <el-table-column
          label="颜色"
          align="center">
          <template slot-scope="scope">
            {{scope.row.color}}
          </template>
        </el-table-column>
        <el-table-column
          label="图片"
          align="center">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100px" height="80px">
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="goodsFrom.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--点击新建的时候触发，弹出一个文本框来-->
      <el-dialog title="上传商品图片" :visible.sync="dialogFormVisible">
        {{imageEntity}}
        <el-form :model="imageEntity">
          <el-form-item label="颜色" :label-width="formLabelWidth">
            <el-input v-model="imageEntity.color" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <el-upload
              class="upload-demo"
              action=""
              :file-list="fileList"
              :http-request="uploadFile">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveFile">确 定</el-button>
        </div>
      </el-dialog>
    </el-tab-pane>
    <el-tab-pane label="扩展属性">
      <el-table
        :data="goodsFrom.goodsDesc.customAttributeItems"
        style="width: 100%">
        <el-table-column
          align="center"
          width="180">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.value"/>
          </template>
        </el-table-column>

      </el-table>
    </el-tab-pane>
    <el-tab-pane label="规格">
      <el-table
        :data="specList"
        style="width: 100%">
        <el-table-column
          align="center"
          width="180">
          <template slot-scope="scope">
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column  align="left">
          <template slot-scope="scope">
            <el-checkbox-group v-model="userOptionList[scope.$index]" size="mini" >
              <el-checkbox :label="option.optionName" border v-for="option in scope.row.options" @change="userSelect"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <!--动态显示用户选择的item表信息-->
      <el-table
        :data="goodsFrom.itemList"
        style="width: 100%">
        <el-table-column :label="spec.attributeName"
                         v-for="spec in goodsFrom.goodsDesc.specificationItems"
                         width="180px" align="center">
          <template slot-scope="scope">
            {{scope.row.spec[spec.attributeName]}}
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>

      <el-button type="primary" @click="save()">保存</el-button>
      <el-button>返回列表</el-button>
  </el-tabs>
</template>

<script>
  export default {
    data() {
      return {
        goodsFrom: {
          goods: {typeTemplateId: '', brandId: '', category1Id: '', category2Id: '', category3Id: ''},       // spu商品表
          goodsDesc: {customAttributeItems: [], specificationItems: [], itemImages: []},   // spu商品描述表
          itemList: [],    // sku商品表
        },
        categories1: [],   // 一级分类
        categories2: [],   // 二级分类
        categories3: [],   // 三级分类
        brandList: [],     // 品牌列表
        specList: [],      // 规格和规格选项列表
        userOptionList: [],// 用户选择的规格列表
        specNames: [],     //规格的名字
        dialogFormVisible: false, // 平常的时候关闭对话框
        imageEntity: {},     // 每次上传的文件对象
        formLabelWidth: '100px',   // 设置大小
        fileList: [],      // 上传的图片列表

      }
    },
    // 通过监听一级分类值的变化来找到对应下面的二级分类
    watch: {
      "goodsFrom.goods.category1Id": function (newV, oldV) {
        // 1. 根据一级分类id值查出对应下的二级分类
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findById/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categories2 = data.categories
          }
        })
      },
      // 2. 通过二级分类的id查出对应的三级分类
      "goodsFrom.goods.category2Id": function (newV, oldV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findById/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categories3 = data.categories
          }
        })
      },
      // 3. 通过三级分类id得到模板id
      "goodsFrom.goods.category3Id": function (newV, oldV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.goodsFrom.goods.typeTemplateId = data.itemCat.typeId
          }
        })
      },
      // 4. 通过模板id得到品牌列表
      "goodsFrom.goods.typeTemplateId": function (newV, oldV) {
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${newV}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            // 为品牌列表赋值
            // 反序列化，将字符串转换为对象，也就是将前端的字符串形式转换为后端的JavaBean形式
            this.brandList = JSON.parse(data.typeTemplate.brandIds)
            // 为扩展属性列表赋值，将模板表里面的数据放到扩展列表里面
            this.goodsFrom.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            //  根据模板id的值变化，得到规格及规格选项的值
            this.$http({
              url: this.$http.adornUrl(`/shop/specification/findSpecAndOptions/${newV}`),
              method: 'get'
            }).then(({data}) => {
              if (data && data.code === 0) {
                console.log("data::::", data)
                // 得到规格选项的值
                this.specList = data.specList
                // 向绑定的用户选择的规格数组中添加子数组
                data.specList.forEach(sp => {
                  this.userOptionList.push([])
                  this.specNames.push(sp.text)
                })
              }
            })
          }
        })
      }
    },
    created() {
      // 查询一级分类
      this.findcategories1()
    },
    methods: {
      // 1. 上传图片保存的方法
      saveFile() {
        this.dialogFormVisible = false
        this.goodsFrom.goodsDesc.itemImages.push(this.imageEntity)
      },

      //2. 用户选择
      userSelect() {
        console.log("userOptionList:", this.userOptionList)
        console.log("specNames:", this.specNames)
        //2.1 为goodsForm.goodsDesc.specificationItems属性赋值
        let specList = []
        for (let i = 0; i < this.specNames.length; i++) {
          specList.push({"attributeName": this.specNames[i], "attributeValue": this.userOptionList[i]})
        }
        //2.2 为this.goodsForm.goodsDesc.specificationItems赋值并处理特殊数据
        this.goodsFrom.goodsDesc.specificationItems = specList.filter(f => f.attributeValue.length > 0)
        //2.3 添加规格列表
        this.addSkuList()
      },
      //3. 添加规格列表
      addSkuList() {
        //3.1 为sku商品列表设置默认值
        this.goodsFrom.itemList = [{spec: {}, num: 9999, price: 100, status: 0, isDefault: 0}]
        //3.2 得到用户选择的规格及规格选项列表
        let specList = this.goodsFrom.goodsDesc.specificationItems
        //3.3 遍历字段,为sku商品列表赋值
        specList.forEach(spec => {
          this.goodsFrom.itemList = this.addColumn(this.goodsFrom.itemList, spec.attributeName, spec.attributeValue)
        })
      },
      //4. 为sku设置值
      addColumn(list, attName, attValue) {
        //4.1 定义一个空的数组
        let arr = []
        //4.2 遍历list
        list.forEach(sp => {
          attValue.forEach(v => {
            //4.2.1 对得到的某件sku商品进行深克隆
            let item = JSON.parse(JSON.stringify(sp))
            item.spec[attName] = v
            arr.push(item)
          })
        })
        return arr
      },

      // 5. 保存数据到数据库
      save(){
        //5.1 处理请求时要添加的数据
        this.goodsFrom.goodsDesc.specificationItems = JSON.stringify(this.goodsFrom.goodsDesc.specificationItems)
        this.goodsFrom.goodsDesc.customAttributeItems = JSON.stringify(this.goodsFrom.goodsDesc.customAttributeItems)
        this.goodsFrom.goodsDesc.itemImages = JSON.stringify(this.goodsFrom.goodsDesc.itemImages)
        this.goodsFrom.itemList.forEach(item=>{
          item.spec = JSON.stringify(item.spec)
        })
        //5.2 向后台发送请求
        this.$http({
          url: this.$http.adornUrl('/shop/goods/save'),
          method: 'post',
          data:this.goodsFrom
        }).then(({data}) => {
          if (data && data.code === 0) {
            //将数据恢复默认值
            this.goodsFrom={
              goods: {typeTemplateId: '', brandId: '', category1Id: '', category2Id: '', category3Id: ''},         //spu商品表
              goodsDesc: {customAttributeItems: [], specificationItems: [], itemImages: []},     //spu商品描述表
              itemList: []       //sku商品列表
            }
            this.fileList = []
          }
        })
      },

      // 6.点击新建按钮的时候触发的方法
      newCreate() {
        this.dialogFormVisible = true
        this.imageEntity = {}
        this.fileList = []
      },

      //7. 文件 上传
      uploadFile(v) {
        //7.1 使用h5的formData对象构造要上传文件
        let data = new FormData()
        data.append("file", v.file)
        //7.2 开始文件上传
        this.$http({
          url: this.$http.adornUrl('/thirdparty/uploadFile'),
          method: 'post',
          header: {"Content-Type": "multipart/form-data"},
          data
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("data", data)
            this.imageEntity.url = data.url
          }
        })
      },

      // 8. 查询一级分类
      findcategories1() {
        this.$http({
          url: this.$http.adornUrl('/shop/itemcat/findById/0'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categories1 = data.categories
          }
        })
      }
    },
  }

</script>
